package internal

import (
	"CaptchaCluster/client/conf"
	"CaptchaCluster/client/machine"
	"CaptchaCluster/defineMsg"
	"CaptchaCluster/log"
	"github.com/name5566/leaf/gate"
	"time"
)

var conns = make(map[gate.Agent]interface{})

func init() {
	skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
	skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
}

var closeCh chan struct{}

func rpcNewAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	_ = a

	log.Release("connection to %s successful", a.RemoteAddr().String())
	sendMachineInfo(a)
	a.WriteMsg(&defineMsg.ReqMachineName{Name: conf.Instance.Name})
}

func sendMachineInfo(a gate.Agent) {
	closeCh = make(chan struct{})
	go func() {
		for {
			select {
			case <-closeCh:
				return
			default:
				a.WriteMsg(&defineMsg.ReqMachineInfo{
					CPUKernel:  machine.Instance.CPUKernel,
					CPUPercent: machine.Instance.CPUPercent,
					MemPercent: machine.Instance.MemPercent,
				})
				time.Sleep(1 * time.Second)
			}
		}
	}()
}

func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	_ = a

	closeCh <- struct{}{}
	close(closeCh)
	a.Close()
}
